import {
  VuexModule,
  Module,
  Mutation,
  Action,
  getModule
  // config
} from 'vuex-module-decorators'
import { RouteConfig } from 'vue-router'
import { asyncRoutes, constantRoutes } from '@/router'
import store from '@/store'

// config.rawError = true
export interface IPermissionState {
  routes: RouteConfig[]
}

@Module({ dynamic: true, store, name: 'permission' })
class Permission extends VuexModule implements IPermissionState {
  routes = constantRoutes

  public get allRoutes() {
    return this.routes
  }

  // ? 设置路由
  @Mutation
  private SET_ROUTES(routes: RouteConfig[]) {
    this.routes = [...constantRoutes, ...routes]
    // this.routes = constantRoutes.concat(asyncRoutes)
  }

  // 筛选路由
  @Action
  public filterRoute() {
    const { menus } = store.getters.roles
    // console.log(menus)
    if (!menus) return []
    const routes = asyncRoutes.filter((item: any) =>
      item.children.map((item2: any) => menus.includes(item2.name))
    )
    // console.log(routes)
    this.SET_ROUTES(routes)
    return routes
  }
}

export const PermissionModule = getModule(Permission)
